package com.topscomm.mpm.xxlJob;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.topscomm.basic.BasicEntity;
import com.topscomm.basic.util.SQLAdapter;
import com.topscomm.cbo.pojo.CboUserEntity;
import com.topscomm.cbo.service.ICboMessageAppService;
import com.topscomm.cbo.service.ICboMessageSysService;
import com.topscomm.cbo.service.impl.CboMessageAppService;
import com.topscomm.mpm.MpmSystemConst;
import com.topscomm.mpm.pojo.MpmProjectChangeEntity;
import com.topscomm.mpm.pojo.MpmProjectEntity;
import com.topscomm.mpm.pojo.MpmProjectSaleEntity;
import com.topscomm.mpm.service.impl.MpmProjectService;
import com.topscomm.mpm.utils.MessageUtil;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.pub.util.StringUtil;
import com.topscomm.tap.common.DatacodeCache;
import com.topscomm.tap.common.ParameterCache;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.JobHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author houyuhang
 * @date 2023/03/11
 * @description: 系统自动判定该线索是否已转化机会点，若未转化则向销售PMO（根据省份匹配）、线索Owner对应人员发送消息提醒
 * @modify:
 */
@JobHandler(value = "sendMessageToLeadOwner")
@Component
public class SendMessageToLeadOwner extends IJobHandler {
    DatacodeCache datacodeCache = new DatacodeCache();
    private static final String PROJECTSOURCETYPE="MpmProjectInfo";
    @Autowired
    private MpmProjectService mpmProjectService;
    @Autowired
    private ICboMessageAppService cboMessageAppService;
    @Autowired
    private ICboMessageSysService cboMessageSysService;

    @Override
    public ReturnT<String> execute(String param) {
        try {
            String weeknum = ParameterCache.getValue("MpmRemindOwnerWeek");
            int dayBefore = Integer.parseInt(weeknum) * 7;
            String purchasePatternBid = MpmSystemConst.PurchasePattern.chanpinBid + "," + MpmSystemConst.PurchasePattern.fuwuBid + "," + MpmSystemConst.PurchasePattern.dianshang;
            // 项目来源为“线索”且采购模式为“产品类招标”、“服务类招标”、“电商招标”时，时间到达“挂网日期”前两周
            StringBufferProxy sql = new StringBufferProxy();
            sql.appendSingle(" mpmproject.state = '9' and projectsource = '{0}' and purchasepattern in ({1}) and {2} = {3} ", MpmSystemConst.MpmProjectSource.lead, purchasePatternBid, SQLAdapter.toChar(MpmProjectSaleEntity.FieldBidbegindate + " - " + dayBefore + ", 'yyyy-mm-dd'"), SQLAdapter.toChar(SQLAdapter.getDate() + ", 'yyyy-mm-dd'"));
            List<Map<String, Object>> mpmProjectList = mpmProjectService.queryMapByWhere(sql.toString(), "queryPolymarizationMapByWhere");
            if (CollectionUtil.isEmpty(mpmProjectList)) {
                return ReturnT.SUCCESS;
            }
            for (Map<String, Object> projectMap : mpmProjectList) {
                String chanceclue = ConvertUtil.convertToString(projectMap.get("chanceclue"));
                String unfinishClue = this.getUnfinishChanceclue(chanceclue);
                if (!StringUtil.isEmpty(unfinishClue)) {
                    this.sendLeadMessageToPMO(unfinishClue, projectMap, weeknum);
                    this.sendLeadMessageToOwner(unfinishClue, projectMap, weeknum);
                }
            }
            return ReturnT.SUCCESS;
        } catch (Exception e) {
            return new ReturnT<>(ReturnT.FAIL_CODE, e.getMessage());
        }
    }
    /**
     * @author houyuhang
     * @date 2023/03/11
     * @description: 获取没有转换为机会点的线索编号
     * @modify:
     */
    public String getUnfinishChanceclue(String chanceclue) {
        String[] splitclue = chanceclue.split(",");
        StringBuilder res = new StringBuilder();
        for (String tempStr : splitclue) {
            StringBufferProxy sql = new StringBufferProxy();
            sql.appendSingle(" select id from ltcchancebackbone where leadcode = '{0}' and MANUSCRIPTSTATUS = '9' ", tempStr);
            List<Map<String, Object>> leadList = mpmProjectService.selectExecute(sql.toString());
            // 如果查不到对应的机会点，说明线索没有转化为机会点
            if (CollectionUtil.isEmpty(leadList)) {
                res.append(tempStr).append(",");
            }
        }
        return res.length() > 0 ? res.substring(0, res.length() - 1) : res.toString();
    }
    /**
     * @author houyuhang
     * @date 2023/03/11
     * @description: 销售PMO接收线索信息
     * @modify:
     */
    public void sendLeadMessageToPMO(String unfinishClue, Map<String, Object> projectMap, String weeknum) {
        // 销售PMO接收线索App和系统消息
        List<Map<String, Object>> appList = new ArrayList<>();
        List<Map<String, Object>> sysList = new ArrayList<>();
        List<Map<String, Object>> receiverList = mpmProjectService.getMessageReceiverPMO(ConvertUtil.convertToString(projectMap.get("deptcommoncode")));
        if (CollectionUtil.isEmpty(receiverList)) {
            return;
        }
        String title = "线索未转化机会点提醒";
        String projectLevel = datacodeCache.getValueDynamic("MpmProjectLevel", ConvertUtil.convertToString(projectMap.get("projectlevel")), "code", "name");
        StringBufferProxy content = new StringBufferProxy();
        content.appendSingle("【{0}级项目：{1}】距挂网还有{2}周时间，项目来源线索【{3}】仍未转化为机会点。", projectLevel, ConvertUtil.convertToString(projectMap.get("projectname")), weeknum, unfinishClue);
        for (Map<String, Object> receiver : receiverList) {
            appList.add(MessageUtil.createMessageAppMap(ConvertUtil.convertToString(receiver.get("usercode")), title, content.toString(), ConvertUtil.convertToLong(projectMap.get("id")),
                    PROJECTSOURCETYPE, 0));
            sysList.add(MessageUtil.createMessageSysMap(ConvertUtil.convertToString(receiver.get("usercode")), ConvertUtil.convertToString(receiver.get("username")), title, content.toString(),
                    ConvertUtil.convertToLong(projectMap.get("id")), PROJECTSOURCETYPE));
        }
        cboMessageAppService.insertList(appList);
        cboMessageSysService.insertList(sysList);
    }
    /**
     * @author houyuhang
     * @date 2023/03/11
     * @description: 线索owner接收线索信息
     * @modify:
     */
    public void sendLeadMessageToOwner(String unfinishClue, Map<String, Object> projectMap, String weeknum) {
        // 线索owner接收线索App和系统消息
        List<Map<String, Object>> appList = new ArrayList<>();
        List<Map<String, Object>> sysList = new ArrayList<>();
        String selectClue = "'" + unfinishClue.replaceAll(",", "','") + "'";
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle(" select id, gardenercode, gardenername from ltcleadbackbone where code in ({0}) ", selectClue);
        List<Map<String, Object>> receiverList = mpmProjectService.selectExecute(sql.toString());
        if (CollectionUtil.isEmpty(receiverList)) {
            return;
        }
        Map<String, Object> receiver = receiverList.get(0);
        String title = "线索未转化机会点提醒";
        StringBufferProxy content = new StringBufferProxy();
        content.appendSingle("由您创建的线索【{0}】立项的项目距挂网还有{1}周时间，请尽快将线索转化为机会点。", unfinishClue, weeknum);
        appList.add(MessageUtil.createMessageAppMap(ConvertUtil.convertToString(receiver.get("gardenercode")), title, content.toString(), ConvertUtil.convertToLong(projectMap.get("id")),
                PROJECTSOURCETYPE, 0));
        sysList.add(MessageUtil.createMessageSysMap(ConvertUtil.convertToString(receiver.get("gardenercode")), ConvertUtil.convertToString(receiver.get("gardenername")), title, content.toString(),
                ConvertUtil.convertToLong(projectMap.get("id")), PROJECTSOURCETYPE));
        cboMessageAppService.insertList(appList);
        cboMessageSysService.insertList(sysList);
    }
}
